import axios from 'axios';
import fs from 'fs';
import path from 'path';
import extract from 'extract-zip';

const pj_dir = process.cwd();
export const PLUGINS_DIR = path.join(process.cwd(), 'src/plugins');

export async function downloadPlugin(pluginId: string, downloadUrl: string) {
  const download_Dir = path.join(PLUGINS_DIR, 'downloads');
  console.log('project dir:', pj_dir);
  console.log(Buffer.from(`project dir: ${pj_dir}`, 'utf8'));
  console.log('download:', download_Dir);
  const zipPath = path.join(download_Dir, `${pluginId}.zip`);
  const pluginTargetDir = path.join(PLUGINS_DIR, pluginId);
  console.log('pluginTargetDir:', pluginTargetDir);

  if (!fs.existsSync(download_Dir)) {
    fs.mkdirSync(download_Dir, { recursive: true });
  }
  try {
    const response = await axios.get(downloadUrl, { responseType: 'arraybuffer' });
    // 使用Buffer.from()替代隐式的Buffer构造函数
    const buffer = Buffer.from(response.data);
    fs.writeFileSync(zipPath, buffer);

    // 添加文件校验
    const fileStats = fs.statSync(zipPath);
    if (fileStats.size === 0) {
      throw new Error(`no download file: ${zipPath}`);
    }

    console.log(`start extract to ${pluginTargetDir}`);
    await extract(zipPath, { dir: PLUGINS_DIR });
    console.log(`extract finished: ${pluginId}`);
  } catch (error: any) {
    console.error(`plugin [${pluginId}] `, error.message);
    throw new Error(`extract failed: ${error.message}`);
  } finally {
    try {
      if (fs.existsSync(zipPath)) {
        fs.unlinkSync(zipPath);
        console.log(`删除${zipPath}`);
      }
    }catch(err: any) {
      console.error(`${zipPath}`, err);
    }
  }
}

export async function deletePlugin(pluginId: string) {
  const pluginDir = path.join(PLUGINS_DIR, pluginId);
  try {
    if (fs.existsSync(pluginDir)) {
      fs.rmSync(pluginDir, { recursive: true, force: true });
      console.log(`插件目录已删除: ${pluginDir}`);
      return true;
    }
    return false;
  } catch (error: any) {
    console.error(`删除插件失败 [${pluginId}]:`, error.message);
    throw new Error(`删除失败: ${error.message}`);
  }
}